package org.chen.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.chen.service.AlertService;
import org.chen.service.SystemConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class AlertServiceImpl implements AlertService {
    
    @Autowired
    private SystemConfigService systemConfigService;

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;
    
    /**
     * 发送普通告警
     */
    @Override
    public void sendAlert(String title, String content) {
        try {
            String adminEmails = systemConfigService.getValueByKey("admin_alert_emails");
            
            if (StrUtil.isBlank(adminEmails)) {
                log.warn("未配置管理员告警邮箱");
                return;
            }
            
            String[] emails = adminEmails.split(",");
            
            for (String email : emails) {
                sendHtmlEmail(
                    email.trim(),
                    "[告警] " + title,
                    buildAlertEmailContent(title, content, "warning")
                );
            }
            
            log.info("告警邮件已发送：{}", title);
            
        } catch (Exception e) {
            log.error("发送告警邮件失败", e);
        }
    }
    
    /**
     * 发送紧急告警（可扩展为短信、电话等）
     */
    @Override
    public void sendUrgentAlert(String title, String content) {
        try {
            // 发送邮件
            String adminEmails = systemConfigService.getValueByKey("admin_urgent_alert_emails");
            if (StrUtil.isNotBlank(adminEmails)) {
                String[] emails = adminEmails.split(",");
                for (String email : emails) {
                    sendHtmlEmail(
                        email.trim(),
                        "[紧急告警] " + title,
                        buildAlertEmailContent(title, content, "urgent")
                    );
                }
            }
            
            log.info("紧急告警已发送：{}", title);
            
        } catch (Exception e) {
            log.error("发送紧急告警失败", e);
        }
    }
    
    /**
     * 发送每日对账报告
     */
    @Override
    public void sendDailyReconciliationReport(Date date,
                                              int totalOrders,
                                              int mismatchCount,
                                              List<String> mismatchOrders) {
        try {
            String adminEmails = systemConfigService.getValueByKey("admin_report_emails");
            
            if (StrUtil.isBlank(adminEmails)) {
                return;
            }
            
            StringBuilder content = new StringBuilder();
            content.append("<h2>每日对账报告</h2>");
            content.append("<p>对账日期：").append(DateUtil.formatDate(date)).append("</p>");
            content.append("<p>总订单数：").append(totalOrders).append("</p>");
            content.append("<p>异常订单数：").append(mismatchCount).append("</p>");
            
            if (mismatchCount > 0) {
                content.append("<h3>异常订单列表：</h3>");
                content.append("<ul>");
                for (String orderNo : mismatchOrders) {
                    content.append("<li>").append(orderNo).append("</li>");
                }
                content.append("</ul>");
                content.append("<p style='color:red;'>请尽快处理以上异常订单！</p>");
            } else {
                content.append("<p style='color:green;'>所有订单对账一致，无异常。</p>");
            }
            
            String[] emails = adminEmails.split(",");
            for (String email : emails) {
                sendHtmlEmail(
                    email.trim(),
                    "[每日对账报告] " + DateUtil.formatDate(date),
                    content.toString()
                );
            }
            
            log.info("每日对账报告已发送");
            
        } catch (Exception e) {
            log.error("发送每日对账报告失败", e);
        }
    }
    
    /**
     * 构建告警邮件内容
     */
    private String buildAlertEmailContent(String title, String content, String level) {
        String color = "warning".equals(level) ? "#ff9800" : "#f44336";
        
        return String.format(
            "<div style='padding:20px;background-color:#f5f5f5;'>" +
            "<div style='background-color:white;padding:20px;border-radius:8px;'>" +
            "<h2 style='color:%s;border-left:4px solid %s;padding-left:10px;'>%s</h2>" +
            "<div style='margin-top:20px;line-height:1.8;'>%s</div>" +
            "<hr style='margin:20px 0;border:none;border-top:1px solid #ddd;'/>" +
            "<p style='color:#999;font-size:12px;'>系统自动告警 | 发送时间：%s</p>" +
            "</div></div>",
            color, color, title, content, DateUtil.now()
        );
    }

    @Override
    public void sendHtmlEmail(String to, String subject, String htmlContent) throws MessagingException, UnsupportedEncodingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

        helper.setFrom(new InternetAddress(from,"Flying Waves"));
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(htmlContent, true);  // 设置为true表示内容为HTML

        javaMailSender.send(message);
    }

    @Override
    public void sendOrderRefundSuccessNotice(String toEmail, String orderId, String adminName) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            helper.setFrom(from);
            helper.setTo(toEmail);
            helper.setSubject("订单退款通知");

            String content = String.format(
                    "尊敬的%s：<br><br>" +
                            "订单 %s 已被用户退款。<br>" +
                            "请及时处理相关后续事宜。<br><br>" +
                            "此致<br>" +
                            "系统自动邮件，请勿回复",
                    adminName, orderId
            );

            helper.setText(content, true);

            javaMailSender.send(message);
            log.info("订单使用通知邮件发送成功，收件人：{}，订单号：{}", toEmail, orderId);
        } catch (Exception e) {
            log.error("订单使用通知邮件发送失败，收件人：{}，订单号：{}，错误信息：{}", toEmail, orderId, e.getMessage());
        }
    }

    @Override
    public void sendOrderRefundFailureNotice(String email, String orderId, String realName) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            helper.setFrom(from);
            helper.setTo(email);
            helper.setSubject("订单退款失败通知");

            String content = String.format(
                    "尊敬的用户：<br><br>" +
                            "您的订单 %s 退款失败。<br>" +
                            "请及时处理相关后续事宜。<br><br>" +
                            "此致<br>" +
                            "系统自动邮件，请勿回复",
                    orderId
            );

            helper.setText(content, true);

            javaMailSender.send(message);
            log.info("订单使用通知邮件发送成功，收件人：{}，订单号：{}", email, orderId);
        } catch (Exception e) {
            log.error("订单使用通知邮件发送失败，收件人：{}，订单号：{}，错误信息：{}", email, orderId, e.getMessage());
        }
    }
}